/*
  Copyright 2007 Anders Båtstrand

      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

 */

package org.dyndns.anderlin.jmplayer.client.ui.binder;

import org.springframework.binding.form.FormModel;
import org.springframework.richclient.form.binding.Binding;
import org.springframework.richclient.form.binding.support.AbstractBinder;
import org.springframework.richclient.form.binding.swing.TextComponentBinding;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.util.Map;

/**
 * This provides a {@link org.springframework.richclient.form.binding.Binder} for {@link Long} that only allows
 * valid "Long" values to be entered into the control.
 */
public class LongBinder extends AbstractBinder {

    public LongBinder() {
        super(Long.class);
    }

    protected JComponent createControl(Map context) {
        return new LongTextField();
    }

    protected Binding doBind(JComponent control, FormModel formModel, String formPropertyPath, Map context) {
        return new TextComponentBinding((JTextComponent) control, formModel, formPropertyPath);
    }

    private static class LongTextField extends JFormattedTextField {
        public boolean isEditValid() {
            final String text = getText();
            if (text == null) return true;
            try {
                Long.parseLong(text);
                return true;
            }
            catch (NumberFormatException e) {
                return false;
            }
        }
    }
}